<?php

namespace app\api\model;


class Product extends BaseModel
{
    /**
     * @var array
     */
    protected $hidden = [
        'delete_time','main_img_id','pivot','from','category_id','create_time','update_time'
    ];

    /**
     * @param $value
     * @param $data
     * @return string
     */
    public function getMainImgUrlAttr($value,$data)
    {
        //资源读取器
        return $this->prefixImgUrl($value,$data);
    }
    public function imgs()
    {
        return $this->hasMany('ProductImage','product_id','id');
    }

    public function properties()
    {
        return $this->hasMany('ProductProperty','product_id','id');
    }


    /**
     * @param $count
     * @return false|\PDOStatement|string|\think\Collection
     */
    public static function getMostRecent($count)
    {
        //create_time是依据字段
        $products = self::limit($count)->order('create_time desc')->select();
        return $products;
    }

    /**
     * @param $categoryID
     * @return false|\PDOStatement|string|\think\Collection
     */
    public static function getProductsByCategoryID($categoryID)
    {
        $products = self::where('category_id','=',$categoryID)->select();
        return $products;
    }

    public static function getProductDetail($id)
    {
        //Query查询构造器
        $product = self::with([
            'imgs' => function($query){
                $query->with(['imgUrl'])->order('order','asc');
            }
        ])
            ->with(['properties'])
            ->find($id);
        return $product;
    }
}
